import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;

public class Receiver extends Thread{
	
	public ArrayList<MachineData> mData;
	public String ip;
	public int port;
	public DatagramSocket serverSocket;
	public ArrayBlockingQueue<MachineData> queue;
	
	public Receiver(ArrayList<MachineData> mData, int m, DatagramSocket serverSocket, ArrayBlockingQueue<MachineData> queue) {
	
		this.mData = mData;
		ip = mData.get(m).name;
		port = mData.get(m).port;
		this.serverSocket = serverSocket;
		this.queue = queue;
	}
	
	public void run() {
		
		byte[] receiveData = new byte[1];
		InetAddress IPAddress = null;
		
		while(true) {
			
			DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            
			try {
				serverSocket.receive(receivePacket);
			}
			catch(IOException e) {
				e.printStackTrace();
			}
			
			byte b = receivePacket.getData()[0];
            IPAddress = receivePacket.getAddress();
            int port = receivePacket.getPort();
            //System.out.println("My IP: " + this.ip + " My Port: " + this.port + " Sender IP: " + IPAddress.toString() + " Sender Port: " + port + " Message: " + sentence);
            
            MachineData m = new MachineData(IPAddress.getHostAddress(), port, b);
            
            try {
				queue.put(m);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}

}
